<template>
  <div class="bg-white" style="height: calc(100vh - 80px); overflow-y: auto">
    <Spin :spinning="isSpinning">
      <template v-if="!isUpdate">
        <div class="w-2/3 m-auto">
          <BasicForm @register="registerForm" />
          <div class="w-full text-center mt-2">
            <a-button type="primary" @click="handleSubmit" :loading="isSpinning">确定</a-button>
          </div>
        </div>
      </template>
      <template v-else>
        <Tabs v-model:activeKey="activeKey" centered>
          <TabPane key="1" tab="表单编辑" forceRender>
            <div class="w-2/3 m-auto">
              <BasicForm @register="registerForm" />
              <div class="w-full text-center mt-2">
                <a-button type="primary" @click="handleSubmit" :loading="isSpinning">确定</a-button>
              </div>
            </div>
          </TabPane>
          <TabPane key="2" tab="字段管理">
            <FieldManagement
              :name="dataRef['name']"
              :formCode="dataRef['code']"
              v-if="dataRef['code']"
          /></TabPane>
          <TabPane key="3" tab="到期提醒">
            <ExpirationReminder :code="dataRef['code']" v-if="dataRef['code']" />
          </TabPane>
          <TabPane key="4" tab="显示规则">
            <DisplayRules :formCode="dataRef['code']" v-if="dataRef['code']" />
          </TabPane>
          <TabPane key="5" tab="验证规则">
            <ValidationRules :formCode="dataRef['code']" v-if="dataRef['code']" />
          </TabPane>
          <TabPane key="6" tab="回写设置">
            <div class="w-2/3 m-auto"
              ><Writeback :formCode="dataRef['code']" v-if="dataRef['code']"
            /></div>
          </TabPane>
          <TabPane key="7" tab="事件脚本">
            <EventDesign :formCode="dataRef['code']" v-if="dataRef['code']" />
          </TabPane>
        </Tabs>
      </template>
    </Spin>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onMounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, checkCode } from './formManagement.data';
  import {
    getFormEditFormPage,
    getFormUpdateForm,
    getFormCreateForm,
  } from '/@/api/formDesign/formDesign';
  import { Tabs, TabPane, Spin } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Writeback } from './writeback';
  import { EventDesign } from './eventDesign';
  import { FieldManagement } from './fieldManagement';
  import { ExpirationReminder } from './expirationReminder';
  import { DisplayRules } from './displayRules';
  import { ValidationRules } from './validationRules';
  import { useTabs } from '/@/hooks/web/useTabs';
  import { useRoute } from 'vue-router';
  export default defineComponent({
    name: 'FormManagementDrawer',
    components: {
      BasicForm,
      Tabs,
      TabPane,
      Writeback,
      EventDesign,
      FieldManagement,
      ExpirationReminder,
      DisplayRules,
      ValidationRules,
      Spin,
    },
    emits: ['success', 'register', 'close'],
    setup(_, { emit }) {
      const { setTitle, closeCurrent } = useTabs();
      const route = useRoute();
      const isUpdate = ref(true);
      let dataRef = ref({});
      const activeKey = ref('1');
      const { createMessage } = useMessage();
      const isSpinning = ref(false);
      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema, resetSchema }] =
        useForm({
          labelWidth: 90,
          schemas: formSchema,
          showActionButtonGroup: false,
        });

      const fetch = async (params) => {
        const query = route.query;
        let data = {};
        let formCode = '';
        console.log('query', query);
        if (query.info) {
          data = JSON.parse(query.info);
          formCode = data.record.code;
          setTitle(query.title);
          isUpdate.value = data?.isUpdate;
        } else if (query.type || query.formCode) {
          // 从流程设计器进入
          formCode = query.formCode;
          isUpdate.value = true;
        } else {
          data = params;
          formCode = data.record.code;
          isUpdate.value = data?.isUpdate;
        }
        isSpinning.value = false;
        activeKey.value = '1';
        dataRef.value = {};
        console.log('data', data);
        try {
          isSpinning.value = true;
          if (unref(isUpdate)) {
            const res = await getFormEditFormPage({ code: formCode });
            dataRef.value = {
              ...res,
              isFlow: res.isFlow ? '1' : '0',
              hasAttachment: res.hasAttachment ? '1' : '0',
            };
            console.log('dataRef', unref(dataRef));
            formSchema[0].componentProps.readonly = true;
            delete formSchema[0].rules;
            resetSchema(formSchema);
            resetFields();
            // updateSchema([
            //   {
            //     field: 'code',
            //     rules: [{}],
            //     componentProps: {
            //       readonly: true,
            //     },
            //   },
            // ]);
            setFieldsValue({
              ...unref(dataRef),
            });
          } else {
            dataRef.value = {
              ...data?.record,
              isOnlyCamera: false,
              viewRuleMode: false,
            };
            console.log('unref(dataRef)', unref(dataRef));

            formSchema[0].componentProps.readonly = false;
            formSchema[0].rules = [{ validator: checkCode, trigger: 'blur' }];
            resetSchema(formSchema);
            resetFields();
            // updateSchema([
            //   {
            //     field: 'code',
            //     // rules: [{ validator: checkCode, trigger: 'blur' }],
            //     componentProps: {
            //       readonly: false,
            //     },
            //   },
            // ]);
            setFieldsValue({
              ...unref(dataRef),
            });
          }
        } catch (error) {
          console.log(error);
        } finally {
          isSpinning.value = false;
        }
      };
      onMounted(fetch);

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        try {
          console.log('dataRef111', unref(dataRef));
          const values = await validate();
          console.log('values', values);
          let formData = Object.assign({}, unref(dataRef), values);
          formData.isFlow = formData.isFlow == '1' ? true : false;
          formData.hasAttachment = formData.hasAttachment == '1' ? true : false;
          console.log('formData', formData);
          isSpinning.value = true;
          if (!unref(isUpdate)) {
            //参数都是必填，导致报错500
            await getFormCreateForm(formData);
          } else {
            await getFormUpdateForm(formData);
          }
          createMessage.success('操作成功');
          if (!unref(isUpdate)) {
            emit('close');
          }
          emit('success');
        } finally {
          isSpinning.value = false;
          isSpinning.value = false;
        }
      }

      return {
        registerForm,
        getTitle,
        handleSubmit,
        activeKey,
        dataRef,
        isUpdate,
        isSpinning,
        fetch,
      };
    },
  });
</script>
